Membership tests: Python’s if in + if not in · Kodify 您所在的位置:网站首页 for c in s 在python Membership tests: Python’s if in + if not in · Kodify

Membership tests: Python’s if in + if not in · Kodify

#Membership tests: Python’s if in + if not in · Kodify| 来源: 网络整理| 查看: 265

With if statements we look for specific situations. That can include some number comparison. Sometimes we have to see if some value is included in another value, like a substring that’s part of a larger string. Let’s see how we make those if statement tests.

IN THIS ARTICLE:

# See if a value contains another: Python’s in operator

The in operator performs a membership test. That tells us if some value contains another value (Python Docs, n.d.). For instance, x in s returns True when x is a member of s. When x does not contain s, that test returns False.

That sounds abstract, but that’s because in is so flexible: we can use it in multiple situations with different values. in makes it possible to see if a string contains a substring, whether a list has a certain value, or whether a dictionary contains a particular key (Lutz, 2013; Sweigart, 2015).

That True or False value that in returns goes well with if statements. There are roughly two ways to use in that way:

We can use in to test membership (see if some value is inside a string, list, dictionary, and so on). When we combine in with not, we can test for a lack of membership: see if some value is not inside a string, list, or dictionary.

Let’s take a closer look at these two approaches.

# If statements that check for values: if with in

When an if statement uses the in operator, it can see if a particular value is present. Let’s see how those work.

# See if a string contains a value with an if statement

With the in operator we can see if a string contains some other value. When the string indeed contains a so-called substring, in returns True. Else we get a False value. Those are the values that our if statement can make decisions with.

Here’s an example Python program:

exampleStr = "Python is a general-purpose programming language." # Look for substring in source string if 'gene' in exampleStr: print("Found! The string contains the phrase 'gene'.") else: print("Didn't find the substring.")

We first make the exampleStr variable. Then an if/else statement has the in operator see whether exampleStr contains the 'gene' phrase. When it does, that tests True.

That value makes our if code execute, where print() says we found the phrase. Should that test be False, the else code says we didn’t find the substring.

Luckily the phrase we search is there, and so the output is:

Found! The string contains the phrase 'gene'. # If statement that sees if a list has a certain value

Another way to use the in operator is to see if some list has a particular value. Here’s how we handle that situation with an if/else statement:

# Consecutive sick days for employees sickDays = [2, 1, 0, 0, 5, 8, 4, 9] # Check for 9 absence days if 9 in sickDays: print('Ouch, someone was sick 9 days in a row!') else: print("We don't have anyone sick 9 consecutive days.")

This mini-program first makes the sickDays list. The values it has are the number of consecutive sicks days for each employee.

We then evaluate that list with an if/else statement. More precisely, the in operator sees whether the value 9 is inside that list. When it is, that test returns True and the if code runs. Without 9 in the list, that condition is False and the else code executes.

But since our list does have the value 9, the if runs and print() says someone was sick nine days in a row:

Ouch, someone was sick 9 days in a row! # If statement that searches a dictionary key with in

Python’s in operator can also see if a dictionary has a particular key. Here’s how an if/else statement can use that behaviour:

sprintTimes = { 'Sarah': 22.20, 'James': 21.05, 'Michelle': 21.97, 'Zoey': 22.12, } # Check if we have Steve's data if 'Steve' in sprintTimes: print("Steve's sprint time is:", sprintTimes['Steve']) else: print("We don't have Steve's sprint time.")

In this program we first make a dictionary (sprintTimes) with the sprint times of several people. Then we code an if/else statement.

Our condition makes the in operator see if the 'Steve' key appears in the dictionary. When it does, in returns True and the if code runs. There the print() function will output Steve’s time. Should the dictionary lack that particular key, in returns False. That makes the else code run, where print() says we miss Steve’s data.

Because our dictionary indeed has no data on Steve, our in condition tests False and the else code prints the following:

We don't have Steve's sprint time. # See when a value is not there: Python’s if not in

Another option is to combine the in operator with the not logical operator. When we do, we get the inverse True or False value that in gives (Python Docs, n.d.). Say that our in test returns False. Then not in gives us True. Likewise, when in tests True, then not in has a False outcome.

That’s how an if statement can perform logical negation. And, when we combine not with in, we can test if a specific value is not there (Lutz, 2013; Matthes, 2016). That way we can test if a string does not contain a substring. Or whether a list does not contain some value.

When we do those tests in an if statement, our program can make decisions based on the absence of values. Let’s see some programming examples of that.

# If statement that sees if a string misses a substring

When an if statement has a not in test, we can see if a string does not contain some substring. Here’s an example:

exampleStr = ("If you want to deliver results with quantity " "and quality in mind, then paying attention to " "your energy level matters.") # Look if substring misses from string if 'productivity' not in exampleStr: print("The string doesn't have the word 'productivity'.")

Here we first make the exampleStr variable. Its content is some sentence about productivity. Then we code an if statement.

The if statement’s condition checks whether the 'productivity' substring does not appear (not in) the exampleStr variable. That word is indeed not in the example sentence. So that tests True. Because of that Python runs the if statement’s code, where print() says the word doesn’t appear in the string:

The string doesn't have the word 'productivity'. # If statement that tests missing list value

In the same way we can test if a list misses a particular value. Here’s an example mini-program:

testScores = ['A', 'A+', 'D', 'C', 'C', 'E', 'A'] # Look if the list doesn't contain 'F' if 'F' not in testScores: print('Nobody scored an F on the test!')

We first make the testScores list here. Its values are letters with the test scores of different people. We want to know if someone got an ‘F’.

So an if statement tests whether 'F' does not appear (not in) the list. Because that letter is indeed missing, that condition tests True. That makes Python run the if statement’s code. That code has print() say nobody achieved an ‘F’:

Nobody scored an F on the test! # If statement that checks for missing dictionary key

Of course an if statement can also test if a dictionary misses a particular key. Here’s how that looks:

linesOfCode = { 'PrintScreenApp': 1280, 'Echo': 20, 'TheNextBigThing': 2583, 'WebCrawler': 204, } # See if list lacks 'BackupApp' if 'BackupApp' not in linesOfCode: print("We don't have statistics for 'BackupApp'.")

First make we a dictionary (linesOfCode). To it we add four key/value pairs. The key of each pair is the name of an application; the value is the number of lines that the app has.

Now we wonder if we miss data for the ‘BackupApp’ program. So with an if statement we see if 'BackupApp' is not a key in the dictionary (not in). Since the app is indeed missing, that condition tests True and the if statement’s code run. There the print() function says we lack data on that program:

We don't have statistics for 'BackupApp'. # Other ways to code Python if statement conditions

Besides coding tests with in and not in, there are other ways to program if statement conditions in Python:

In evaluate values with if statements we see how our conditions can compare one value against another. Logical negation with if statements discusses how an if statement can test if something did not happen. And test multiple conditions with if statements explains how a single if or if/else statement can test several scenarios at the same time.

For much more on if statements, see all if statement articles.

# Summary

With the in operator we see if some value contains another value. That is, x in s returns True when x is a member of s. When we use in with if statements, our code can tell if a string contains a substring, whether a list has a specific value, or if a dictionary has a certain key.

Our if statements can also make decisions based on the opposite. We do that with not in. That tests True when a string, list, or dictionary lacks the value we look for. When the tested value is there, not in returns False.

References

Lutz, M. (2013). Learning Python (5th Edition). Sebastopol, CA: O’Reilly Media.

Matthes, E. (2016). Python Crash Course: A Hands-On, Project-Based Introduction to Programming. San Francisco, CA: No Starch Press.

Python.org (n.d.). Expressions. Retrieved on August 5, 2019, from https://docs.python.org/3/reference/expressions.html

Sweigart, A. (2015). Automate The Boring Stuff With Python: Practical Programming for Total Beginners. San Francisco, CA: No Starch Press.

Published September 6, 2019. # Related Python tutorials If statements that test the opposite: Python’s if not explained

Most Python if statements look for a specific situation. But we can also execute code when a specific condition did not happen. We do that with not.

Python’s if statement explained: execute code conditionally

Python’s if statements make decisions by evaluating a condition. When True, code indented under if runs. Else our program continues with other code.

Test multiple conditions with a Python if statement: and and or explained

Python’s if statements test multiple conditions with and and or. Those logical operators combine several conditions into a single True or False value.

Python’s nested if statements: if code inside another if statement

A nested if statement is an if clause placed inside an if or else code block. They make checking complex Python conditions and scenarios possible.

Python’s if/else statement: choose between two options programmatically

The if/else statement has Python make decisions. When the condition tests True, code intended under if runs. Otherwise the else code executes.

« All Python if/else articles


【本文地址】

公司简介

联系我们

今日新闻

    推荐新闻

    专题文章
      CopyRight 2018-2019 实验室设备网 版权所有